package com.example.springboot.service.impl;

import com.example.springboot.Exception.ServiceException;
import com.example.springboot.common.Page;
import com.example.springboot.service.OrdersProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单-商品关系表(OrdersProduct)表服务实现类
 *
 * @author makejava
 * @since 2024-01-13 17:16:26
 */
@Service("ordersProductService")
public class OrdersProductServiceImpl implements OrdersProductService {
    @Autowired
    private OrdersProductMapper ordersProductMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private StoreMapper storeMapper;

    @Override
    public List<OrdersProduct> selectByOrderId(Integer orderId) {
        try {
            return ordersProductMapper.selectByOrderId(orderId);
        } catch (Exception e) {
            throw new ServiceException("获取订单商品关系表失败");
        }
    }

    /**
     * 通过orders_product关系表统计该所有商品下订单的count(*)
     *
     * @param productId
     * @return
     */
    @Override
    public BigDecimal selectOrderCountByProductId(Integer productId) {
        try {
            int count = ordersProductMapper.selectOrderCountByProductId(productId);
            return new BigDecimal(count);
        } catch (Exception e) {
            throw new ServiceException("获取订单商品关系表失败");
        }
    }

    @Override
    public Page<OrdersProduct> selectByPageInStore(Integer currentPage, Integer pageSize, Integer storeId) {
        try {
            // 计算起始行
            Integer startRow = (currentPage - 1) * pageSize;

            // 获取商家的所有商品

            // 根据订单和商品的关系获取关于商家的所有订单
            List<OrdersProduct> storeAllOrders = ordersProductMapper.selectByStoreId(storeId);
            int orderCount = storeAllOrders.size();

            // 分页获取商家的订单
            List<OrdersProduct> ordersProducts = ordersProductMapper.selectStoreInPage(startRow, pageSize, storeId);
         /*   // 查找商家的所有的商品
            List<Product> products = productMapper.selectByStoreId(storeId);
            List<Integer> productIds = products.stream().map(Product::getId).distinct().collect(Collectors.toList());


            // 获取该商家下的订单数量
            int orderCount = ordersProductMapper.selectOrderCountByProductIds(productIds);
            // 查找关系表中商品id在productIds中的订单信息
            List<OrdersProduct> ordersProducts = ordersProductMapper.selectByProductIds(startRow, pageSize, productIds);
*/
            Page<OrdersProduct> page = new Page<>();
            page.setList(ordersProducts);
            page.setTotal(orderCount);
            return page;
        } catch (Exception e) {
            throw new ServiceException("获取订单商品关系表失败");
        }
    }

    @Override
    public Page<OrdersProduct> selectByManyCondition(Integer currentPage, Integer pageSize, String number, Integer storeId, Integer userId, String startTime, String endTime, Integer status) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startDate = null;
            Date endDate = null;
            // 数据为''的转为null

            if ("".equals(currentPage)) {
                currentPage = null;
            }
            if ("".equals(pageSize)) {
                pageSize = null;
            }
            if ("".equals(number)) {
                number = null;
            }
            if ("".equals(storeId)) {
                storeId = null;
            }
            if ("".equals(userId)) {
                userId = null;
            }
            if ("".equals(startTime)) {
                startTime = null;
            } else {
                startDate = dateFormat.parse(startTime);
            }
            if ("".equals(endTime)) {
                endTime = null;
            } else {
                endDate = dateFormat.parse(endTime);
            }
            if ("".equals(status)) {
                status = null;
            }

            Integer startRow = (currentPage - 1) * pageSize;
            // 先查orders符合条件的
            // 再查orders_product符合条件的
            // 先查总数
            // 在分页查找

            // 查总数
//            List<Orders> totalOrders = ordersMapper.selectByNumberAndUserIdAndStartTimeAndEndTimeAndStatus(number, userId, startDate, endDate, status);
            List<Orders> totalOrders = ordersMapper.selectByNumberAndUserIdAndStartTimeAndEndTimeAndStatus(number, userId, startDate, endDate, status);
            // 获取订单集合中的ids
            List<Integer> totalOrdersIds = totalOrders.stream().map(Orders::getId).distinct().collect(Collectors.toList());
            if (totalOrdersIds.size() == 0) {
                // 返回分页数据
                Page<OrdersProduct> page = new Page<>();
                page.setTotal(0);
                page.setList(null);
                return page;
            }
            // 在关系表中查找该商家下的所有订单
            boolean needInPage = false;
            List<OrdersProduct> totalOrdersProducts = ordersProductMapper.selectByStoreIdInOrdersIds(startRow, pageSize, storeId, totalOrdersIds, needInPage);
            int totalCount = totalOrdersProducts.size();

            // 查分页数据
            needInPage = true;
            List<OrdersProduct> ordersProducts = ordersProductMapper.selectByStoreIdInOrdersIds(startRow, pageSize, storeId, totalOrdersIds, needInPage);

            // 返回分页数据
            Page<OrdersProduct> page = new Page<>();
            page.setTotal(totalCount);
            page.setList(ordersProducts);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取订单商品关系表失败");
        }
    }

    @Override
    public void send(Integer id) {
        try {
            Integer status = 2;
            ordersProductMapper.updateStatusById(id, status);
        } catch (Exception e) {
            throw new ServiceException("发货失败");
        }
    }

    @Override
    public Page<OrdersProduct> selectByPage(Integer currentPage, Integer pageSize) {
        // 计算起始行
        Integer startRow = (currentPage - 1) * pageSize;

        // 获取商家的所有商品

        // 根据订单和商品的关系获取关于商家的所有订单
        List<OrdersProduct> storeAllOrders = ordersProductMapper.selectAll();
        int orderCount = storeAllOrders.size();

        // 分页获取商家的订单
        List<OrdersProduct> ordersProducts = ordersProductMapper.selectInPage(startRow, pageSize);
         /*   // 查找商家的所有的商品
            List<Product> products = productMapper.selectByStoreId(storeId);
            List<Integer> productIds = products.stream().map(Product::getId).distinct().collect(Collectors.toList());


            // 获取该商家下的订单数量
            int orderCount = ordersProductMapper.selectOrderCountByProductIds(productIds);
            // 查找关系表中商品id在productIds中的订单信息
            List<OrdersProduct> ordersProducts = ordersProductMapper.selectByProductIds(startRow, pageSize, productIds);
*/
        Page<OrdersProduct> page = new Page<>();
        page.setList(ordersProducts);
        page.setTotal(orderCount);
        return page;
    }

    @Override
    public void deleteById(Integer id) {
        try {
            ordersProductMapper.deleteById(id);
        } catch (Exception e) {
            throw new ServiceException("删除订单失败");
        }
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        try {
            for (Integer id : ids) {
                ordersProductMapper.deleteById(id);
            }
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }
    }

    @Override
    public List<OrdersProduct> loadByOrderId(Integer orderId) {
        try {
            return ordersProductMapper.selectByOrderId(orderId);
        } catch (Exception e) {
            throw new ServiceException("加载订单商品关系表失败");
        }
    }

    @Override
    @Transactional
    public void confirmReceipt(Integer id) {
        try {
            ordersProductMapper.confirmReceipt(id);
            //确认收货后，给商家增加余额
            OrdersProduct ordersProduct = ordersProductMapper.selectAllById(id);
            Store store = ordersProduct.getStore();
            store.setSurplus(store.getSurplus().add(ordersProduct.getProduct().getPrice().multiply(new BigDecimal(ordersProduct.getNum()))));
            storeMapper.updateById(store);
        } catch (Exception e) {
            throw new ServiceException("确认收货失败");
        }
    }
}
